import { defineStore } from 'pinia';
import axios from '@/plugins/http';
import { showToast, showConfirmDialog } from 'vant';
import { ref, computed } from 'vue';
import router from '@/router';
const useCartStore = defineStore('cart', () => {
    // 购物车列表
    const cartList = ref([]);
    // ************actions************//
    // 重置购物车列表
    const cartListInit = (payload) => {
        cartList.value = payload;
    }
    // 更新全选复选框的状态
    const updateAllChecked = (payload) => {
        // 更新每一个商品选中状态
        cartList.value.forEach(item => {
            item.status = payload;
        });
    }
    // 添加购物车
    const cartAddAction = async (payload) => {
        const { uid } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
        if (!uid) {
            const result = await showConfirmDialog({
                title: '提示',
                message: '您还没有登录, 确认登录?',
                overlay: false
            }).catch(() => null);
            if (result) {
                router.push({ name: "login", query: { url: router.currentRoute.fullPath } });
            }
            return false;
        }
        axios.post('/cartadd', { uid, ...payload }).then(res => {
            if (res.code === 200) {
                showToast(res.msg);
                getCartList();
            }
        });
    }

    // 更新所有商品的选中状态
    const updateAllCheckedAction = (payload) => {
        const { uid } = JSON.parse(localStorage.getItem("userLoginInfo") || '{}');
        const status = payload ? 1 : 0;
        axios.post('/cartUpdateAllChecked', { uid, status }).then((res) => {
            if (res.code === 200) {
                updateAllChecked(status);
            }
        });
    }
    // 请求购物车列表
    const getCartList = (callback) => {
        const { uid } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
        if (!uid) {
            return showConfirmDialog({
                title: "提示",
                message: '您还没有登录,确认登录?',
                overlay: false
            })
                .then(() => {
                    // on confirm
                    router.push({ name: "login", query: { url: router.currentRoute.value.fullPath } });
                })
                .catch(() => {
                    // on cancel
                });
        }
        axios.get('/cartlist', { params: { uid } }).then(res => {
            if (res.code === 200) {
                cartList.value = res.list ? res.list : [];
                setTimeout(() => {
                    callback && callback();
                }, 300);
            }
        });
    }
    // 删除购物车商品
    const cartDelAction = (payload) => {
        axios.post('/cartdelete', { id: payload }).then(res => {
            if (res.code === 200) {
                // 根据id查找索引
                const index = cartList.value.findIndex(item => item.id === payload);
                cartList.value.splice(index, 1);
            }
        });
    }

    // ************getters************//
    //计算购物车总价
    const cartPrice = computed(() => {
        let price = 0;
        cartList.value.forEach(item => {
            if (item.status == 1) {
                price += item.price * item.num;
            }
        });
        // 将计算单位改为分
        return parseFloat(price * 100);
    })

    // 计算全选复选框选中状态
    const originAllChecked = computed(() => {
        let checked = true;
        cartList.value.forEach(item => {
            if (item.status == 0) {
                checked = false;
            }
        });
        return checked;
    })

    // 计算购物车商品总数
    const cartGoodsCount = computed(() => {
        let count = 0;
        cartList.value.forEach(item => {
            if (item.status == 1) {
                count += item.num;
            }
        });
        return count;
    })

    return {
        // ************state:************//
        cartList,
        // ************actions:************//
        cartListInit,
        updateAllChecked,
        cartAddAction,
        updateAllCheckedAction,
        getCartList,
        cartDelAction,
        // ************getters:************//
        originAllChecked,
        cartPrice,
        cartGoodsCount
    }
});

export default useCartStore;